module.exports = app => {
    const Router = require("koa-router")
    const router = new Router()
    app.use(router.routes()).use(router.allowedMethods())
    const Car = require("../db/car")
    const bodyParser = require("koa-bodyparser")
    app.use(bodyParser())
    router.get('/car', async ctx => {
        const data = await Car.find().populate("user")
        ctx.body = {
            message: "获取成功",
            status: 200,
            data, //JSON.stringify(data), 要返回子级需要先转换为字符串 在返回处理的时候自动调用JSON.parse() 或者直接在父级关联查询使用.lean()方法 
        }
    })
    router.post('/car', async ctx =>{
        const res = (await Car.find({ name: ctx.request.body.name }))||[]
        if(res.length) {
            ctx.body = {
                message: "添加失败，该名称已存在！",
                status: 400,
            }
        }
        else {
            await Car.create(ctx.request.body)
            const data = await Car.find()
            ctx.body = {
                message: "添加成功",
                status: 200,
                data,
            }
        }
    })
}